package com.lb.shopguide.ui.fragment.guide.recommend;

import android.annotation.SuppressLint;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.recommend.RecommendDetailGoodsBean;
import com.lb.shopguide.entity.recommend.StaffEarnMoneyBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.dialog.DialogSelectRecSku;
import com.lb.shopguide.ui.view.LbCountDownWidgetInDetail;
import com.lb.shopguide.ui.view.marquee.MarqueeView;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.pic.GlideImageLoader;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Create by kangzhao on 2018/12/1
 */
@SuppressLint("SetTextI18n")
public class FragmentRecGoodsFront extends BaseCommonFragment {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.tv_service)
    TextView tvService;
    @BindView(R.id.iv_limit_sale)
    ImageView ivLimitSale;
    @BindView(R.id.layout_service)
    LinearLayout layoutService;
    @BindView(R.id.layout_goods_sale_out)
    RelativeLayout layoutSaleOut;
    @BindView(R.id.layout_sec_will_start)
    RelativeLayout layoutSecWillStart;
    @BindView(R.id.layout_sec_starting)
    RelativeLayout layoutSecStarting;
    @BindView(R.id.layout_goods_ordinary)
    RelativeLayout layoutOrdinary;
    @BindView(R.id.layout_show_category)
    RelativeLayout rlCategory;
    @BindView(R.id.tv_marquee_view)
    MarqueeView mMarqueeView;

    private RecommendDetailGoodsBean mRecommendDetailGoodsBean;

    private ArrayList<StaffEarnMoneyBean> staffEarnMoneyList;

    public static FragmentRecGoodsFront newInstance(RecommendDetailGoodsBean bean) {
        FragmentRecGoodsFront fragmentRecGoodsFront = new FragmentRecGoodsFront();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.GOODS_DETAIL_BEAN, bean);
        fragmentRecGoodsFront.setArguments(bundle);
        return fragmentRecGoodsFront;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_rec_goods_front;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.GOODS_DETAIL_BEAN)) {
            mRecommendDetailGoodsBean = (RecommendDetailGoodsBean) bundle.getSerializable(AppConstant.GOODS_DETAIL_BEAN);
            sendRequestGetStaffInfo(mRecommendDetailGoodsBean.getProductCode());
        }
        staffEarnMoneyList = new ArrayList<>();
    }

    @Override
    public void initView() {
        banner.setImageLoader(new GlideImageLoader());
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);

        bindGoodsDetail();
        initListener();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {

    }

    private void startMarquee() {
        ArrayList<String> marqueeList = new ArrayList<>();
        ArrayList<String> images = new ArrayList<>();
        for (StaffEarnMoneyBean bean : staffEarnMoneyList) {
            marqueeList.add(bean.getStaffName() + "  已赚了" + bean.getBonusMoney());
            images.add(bean.getStaffHeadPicUrl());
        }
        mMarqueeView.startWithList(marqueeList, images);
        mMarqueeView.setVisibility(View.VISIBLE);
    }

    private void hideMarquee() {
        mMarqueeView.setVisibility(View.GONE);
    }

    private void bindGoodsDetail() {
        tvGoodsName.setText(mRecommendDetailGoodsBean.getProductName());
        bindBanner();
        resetGoodsStatus();
        if (mRecommendDetailGoodsBean.getTotalStoreSum() == 0) {
            bindSaleOut(layoutSaleOut);
        } else {
            if (mRecommendDetailGoodsBean.isSecSymbol()) {
                ivLimitSale.setVisibility(View.VISIBLE);
                if (mRecommendDetailGoodsBean.getSecStatus() == AppConstant.GOODS_SEC_NOT_START) {
                    layoutSecWillStart.setVisibility(View.VISIBLE);
                    bindGoodsNotStart(layoutSecWillStart);
                } else if (mRecommendDetailGoodsBean.getSecStatus() == AppConstant.GOODS_SEC_START) {
                    layoutSecStarting.setVisibility(View.VISIBLE);
                    bindGoodsStarting(layoutSecStarting);
                } else if (mRecommendDetailGoodsBean.getSecStatus() == AppConstant.GOODS_SEC_END) {
                    layoutSaleOut.setVisibility(View.VISIBLE);
                    bindSaleOut(layoutSaleOut);
                }
            } else {
                ivLimitSale.setVisibility(View.GONE);
                layoutOrdinary.setVisibility(View.VISIBLE);
                bindOrdinary(layoutOrdinary);
            }
        }

        if (mRecommendDetailGoodsBean.getOnOffSymbol()) {
            tvService.setVisibility(View.VISIBLE);
            StringBuffer sb = new StringBuffer();
            for (String service : mRecommendDetailGoodsBean.getProductServices()) {
                sb.append(service + "·");
            }
            if (sb.length() != 0) {
                tvService.setText(sb.toString().substring(0, sb.length() - 1));
            }
        } else {
            tvService.setVisibility(View.GONE);
        }
        if (ivLimitSale.getVisibility() == View.GONE && tvService.getVisibility() == View.GONE) {
            layoutService.setVisibility(View.GONE);
        }
    }

    private void bindOrdinary(View view) {
        TextView tvGoodsPrice = view.findViewById(R.id.tv_ordinary_goods_price);
        TextView tvEarnGoodsPrice = view.findViewById(R.id.tv_ordinary_earn_price);
        TextView tvOriginGoodsPrice = view.findViewById(R.id.tv_ordinary_origin_goods_price);
        tvGoodsPrice.setText("￥" + mRecommendDetailGoodsBean.getSalePrice());
        tvEarnGoodsPrice.setText("￥" + mRecommendDetailGoodsBean.getStaffBen());
        tvOriginGoodsPrice.setText("￥" + mRecommendDetailGoodsBean.getOrgPrice());
        tvOriginGoodsPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

    }

    private void bindSaleOut(View view) {
        TextView tvSaleOut = view.findViewById(R.id.tv_sale_out);
        tvSaleOut.setText("已售罄 下场秒杀即将开启");
        if (mRecommendDetailGoodsBean.isSecSymbol()) {//秒杀售空
            ivLimitSale.setVisibility(View.VISIBLE);
            layoutSaleOut.setVisibility(View.VISIBLE);
        } else {//普通售空
            layoutSaleOut.setVisibility(View.GONE);
            ivLimitSale.setVisibility(View.GONE);
            layoutOrdinary.setVisibility(View.VISIBLE);
            bindOrdinary(layoutOrdinary);
        }
    }

    private void bindGoodsNotStart(View view) {
        TextView tvPrice = view.findViewById(R.id.tv_will_sale_price);
        TextView tvOriginPrice = view.findViewById(R.id.tv_will_origin_price);
        TextView tvStartTime = view.findViewById(R.id.tv_start_time);

        Date date = TimeUtils.millis2Date(mRecommendDetailGoodsBean.getSecBeginTimeStamp());
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
         if (TimeUtils.isToday(date)) {
            tvStartTime.setText("今天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "开始");
        } else {
            tvStartTime.setText(cal.get(Calendar.MONTH) + 1 + "-" + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "开始");
        }
        LbCountDownWidgetInDetail widget = view.findViewById(R.id.count_down_will_start);
        tvPrice.setText("￥" + mRecommendDetailGoodsBean.getSalePrice());
        tvOriginPrice.setText("原价￥" + mRecommendDetailGoodsBean.getOrgPrice());
        tvOriginPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        widget.setTime(mRecommendDetailGoodsBean.getSecBeginTimeStamp() - System.currentTimeMillis());

        SpannableString sp = new SpannableString(tvPrice.getText().toString());
        sp.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示
        tvPrice.setText(sp);

    }

    private void bindGoodsStarting(View view) {
        TextView tvPrice = view.findViewById(R.id.tv_starting_sale_price);
        TextView tvOriginPrice = view.findViewById(R.id.tv_staring_origin_price);
        LbCountDownWidgetInDetail widget = view.findViewById(R.id.count_down_starting);
        tvPrice.setText("￥" + mRecommendDetailGoodsBean.getSalePrice());
        tvOriginPrice.setText("原价￥" + mRecommendDetailGoodsBean.getOrgPrice());
        tvOriginPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        widget.setTime(mRecommendDetailGoodsBean.getSecEndTimeStamp() - System.currentTimeMillis());

        SpannableString sp = new SpannableString(tvPrice.getText().toString());
        sp.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示
        tvPrice.setText(sp);
    }

    private void resetGoodsStatus() {
        layoutSaleOut.setVisibility(View.GONE);
        layoutSecWillStart.setVisibility(View.GONE);
        layoutOrdinary.setVisibility(View.GONE);
        layoutSecStarting.setVisibility(View.GONE);
    }

    private void bindBanner() {
        banner.setImages(mRecommendDetailGoodsBean.getProductPicUrls());
        banner.start();
    }

    private void initListener() {

    }

    @OnClick(R.id.layout_show_category)
    void onCategoryClick() {
        DialogSelectRecSku dialogSelectSku = DialogSelectRecSku.getDialogSelectSku(mRecommendDetailGoodsBean);
        dialogSelectSku.show(getParentFragment().getFragmentManager(), getPageTag());
        dialogSelectSku.setOnShareClickListener(new DialogSelectRecSku.OnShareClickListener() {
            @Override
            public void onShareClickListener() {
                ((FragmentRecGoodsDetail) getParentFragment()).shareLogic();
            }
        });
    }

    @Override
    public String getPageTag() {
        return FragmentRecGoodsFront.class.getCanonicalName();
    }

    private void sendRequestGetStaffInfo(String productCode) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArray = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonArray.size() != 0) {
                        for (JsonElement obj : jsonArray) {
                            StaffEarnMoneyBean bean = JsonUtil.getGson().fromJson(obj, StaffEarnMoneyBean.class);
                            staffEarnMoneyList.add(bean);
                        }
                        startMarquee();
                    } else {
                        hideMarquee();
                    }

                }
            }
        };
        ApiMethodGuide.listEarnProfitStaff(productCode, new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }
}
